package com.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.pojo.common.PageResult;
import com.crm.pojo.common.Result;
import com.crm.pojo.common.UserContext;
import com.crm.pojo.domain.Business;
import com.crm.pojo.domain.LoginUser;
import com.crm.pojo.dto.BusinessAssignmentDto;
import com.crm.pojo.dto.BusinessDto;
import com.crm.pojo.dto.BusinessGainDto;
import com.crm.service.BusinessService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @Author: xaw
 * @CreateTime: 2025-09-06 17:12:00
 * @Description: 商机控制器
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/business")
public class BusinessController {

    private final BusinessService businessService;

    /**
     * 根据客户ID获取商机详情
     * @param id 客户ID
     * @return 商机详情
     */
    @GetMapping("/{id}")
    public Result<Business> getBusinessById(@PathVariable Integer id) {
        try {
            Business business = businessService.getById(id);
            if (business != null) {
                return Result.success(business);
            } else {
                return Result.error("未找到指定的商机");
            }
        } catch (Exception e) {
            log.error("查询商机详情异常", e);
            return Result.error("查询商机详情异常: " + e.getMessage());
        }
    }

    /**
     * 商机列表查询接口，支持高级搜索
     * @param pageNum 页码
     * @param pageSize 页大小
     * @param id 客户ID
     * @param name 客户姓名
     * @param phone 手机号
     * @param subject 意向学科
     * @param status 商机状态
     * @param params 其他参数
     * @return 分页查询结果
     */
    @GetMapping("/list")
    public PageResult<Business, Object> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer id,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String subject,
            @RequestParam(required = false) String status,
            @RequestParam Map<String, Object> params) {
        
        // 获取时间范围参数
        String beginCreateTime = (String) params.get("beginCreateTime");
        String endCreateTime = (String) params.get("endCreateTime");
        
        // 构建分页对象
        IPage<Business> page = new Page<>(pageNum, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<Business> queryWrapper = new LambdaQueryWrapper<>();
        
        // ID精确查询
        if (id != null) {
            queryWrapper.eq(Business::getId, id);
        }
        
        // 姓名模糊查询
        if (StringUtils.hasText(name)) {
            queryWrapper.like(Business::getName, name);
        }
        
        // 手机号模糊查询
        if (StringUtils.hasText(phone)) {
            queryWrapper.like(Business::getPhone, phone);
        }
        
        // 意向学科精确查询
        if (StringUtils.hasText(subject)) {
            queryWrapper.eq(Business::getSubject, subject);
        }
        
        // 商机状态查询
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(Business::getStatus, status);
        }
        
        // 创建时间范围查询
        if (StringUtils.hasText(beginCreateTime)) {
            queryWrapper.ge(Business::getCreateTime, beginCreateTime);
        }
        if (StringUtils.hasText(endCreateTime)) {
            queryWrapper.le(Business::getCreateTime, endCreateTime);
        }
        
        // 执行分页查询
        queryWrapper.and(wrapper -> wrapper.isNull(Business::getFinishTime)
                .or()
                .eq(Business::getFinishTime, ""));

        businessService.page(page, queryWrapper);
        
        // 获取列表数据
        List<Business> records = page.getRecords();
        
        // 为每个商机查询最新的下次跟进时间

        for (Business business : records) {
            String nextTime = businessService.getLatestNextTime(business.getId());
            business.setNextTime(nextTime);
        }
        
        // 构造返回结果
        PageResult<Business, Object> result = new PageResult<>();
        result.setCode(200);
        result.setMsg("查询成功");
        result.setTotal(page.getTotal());
        result.setRows(records);
        
        return result;
    }
    
    /**
     * 公海池列表查询接口，支持高级搜索
     * @param pageNum 页码
     * @param pageSize 页大小
     * @param id 客户ID
     * @param name 客户姓名
     * @param phone 手机号
     * @param subject 意向学科
     * @param params 其他参数
     * @return 分页查询结果
     */
    @GetMapping("/pool")
    public PageResult<Business, Object> pool(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer id,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String subject,
            @RequestParam Map<String, Object> params) {
        
        // 获取时间范围参数
        String beginCreateTime = (String) params.get("beginCreateTime");
        String endCreateTime = (String) params.get("endCreateTime");
        
        // 构建分页对象
        IPage<Business> page = new Page<>(pageNum, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<Business> queryWrapper = new LambdaQueryWrapper<>();
        // 只查询公海池中的商机
        queryWrapper.eq(Business::getIsPool, 1);
        
        // ID精确查询
        if (id != null) {
            queryWrapper.eq(Business::getId, id);
        }
        
        // 姓名模糊查询
        if (StringUtils.hasText(name)) {
            queryWrapper.like(Business::getName, name);
        }
        
        // 手机号模糊查询
        if (StringUtils.hasText(phone)) {
            queryWrapper.like(Business::getPhone, phone);
        }
        
        // 意向学科精确查询
        if (StringUtils.hasText(subject)) {
            queryWrapper.eq(Business::getSubject, subject);
        }
        
        // 创建时间范围查询
        if (StringUtils.hasText(beginCreateTime)) {
            queryWrapper.ge(Business::getCreateTime, beginCreateTime);
        }
        if (StringUtils.hasText(endCreateTime)) {
            queryWrapper.le(Business::getCreateTime, endCreateTime);
        }
        
        // 执行分页查询
        businessService.page(page, queryWrapper);
        
        // 获取列表数据
        List<Business> records = page.getRecords();
        
        // 为每个商机查询最新的下次跟进时间
        for (Business business : records) {
            String nextTime = businessService.getLatestNextTime(business.getId());
            business.setNextTime(nextTime);
        }
        
        // 构造返回结果
        PageResult<Business, Object> result = new PageResult<>();
        result.setCode(200);
        result.setMsg("查询成功");
        result.setTotal(page.getTotal());
        result.setRows(records);
        
        return result;
    }

    /**
     * 新建商机
     * @param businessDto 商机信息
     * @return 操作结果
     */
    @PostMapping
    public Result<Void> createBusiness(@RequestBody BusinessDto businessDto) {
        // 将DTO转换为实体
        Business business = new Business();
        business.setName(businessDto.getName());
        business.setPhone(businessDto.getPhone());
        business.setChannel(businessDto.getChannel());
        business.setSex(businessDto.getSex());
        business.setAge(businessDto.getAge());
        business.setWeixin(businessDto.getWeixin());
        business.setQq(businessDto.getQq());
        business.setSubject(businessDto.getSubject());
        business.setProvinces(businessDto.getProvinces());
        business.setCity(businessDto.getCity());
        business.setRemark(businessDto.getRemark());
        business.setOccupation(businessDto.getOccupation());
        business.setEducation(businessDto.getEducation());
        business.setMajor(businessDto.getMajor());
        business.setJob(businessDto.getJob());
        business.setSalary(businessDto.getSalary());
        business.setExpectedSalary(businessDto.getExpectedSalary());
        business.setCourseId(businessDto.getCourseId());
        business.setReasons(businessDto.getReasons());
        business.setPlan(businessDto.getPlan());
        business.setPlanTime(businessDto.getPlanTime());
        business.setOtherIntention(businessDto.getOtherIntention());
        
        // 设置地区信息
        if (StringUtils.hasText(businessDto.getProvinces()) && StringUtils.hasText(businessDto.getCity())) {
            business.setRegion(businessDto.getProvinces() + "_" + businessDto.getCity());
        } else if (StringUtils.hasText(businessDto.getProvinces())) {
            business.setRegion(businessDto.getProvinces() + "_null");
        } else if (StringUtils.hasText(businessDto.getCity())) {
            business.setRegion("null_" + businessDto.getCity());
        } else {
            business.setRegion("null_null");
        }
        
        // 设置默认状态为"待跟进"(对应值为0)
        business.setStatus(0);
        
        // 设置为公海池客户
        business.setIsPool(1);
        
        // 设置创建时间和创建者
        LocalDateTime now = LocalDateTime.now();
        business.setCreateTime(now);
        business.setUpdateTime(now);
        
        LoginUser currentUser = UserContext.getCurrentUser();
        if (currentUser != null && StringUtils.hasText(currentUser.getUserName())) {
            business.setCreateBy(currentUser.getUserName());
            business.setUpdateBy(currentUser.getUserName());
        } else {
            business.setCreateBy("admin");
            business.setUpdateBy("admin");
        }
        
        // owner字段初始化为空字符串，表示未分配
        business.setOwner("");
        
        // 保存到数据库
        boolean saved = businessService.save(business);
        
        if (saved) {
            return Result.success();
        } else {
            return Result.error("新增商机失败");
        }
    }
    
    /**
     * 更新商机信息
     * @param business 商机信息
     * @return 操作结果
     */
    @PutMapping
    public Result<Void> updateBusiness(@RequestBody Business business) {
        try {
            // 更新到数据库
            boolean updated = businessService.updateById(business);
            
            if (updated) {
                return Result.success();
            } else {
                return Result.error("更新商机失败");
            }
        } catch (Exception e) {
            log.error("更新商机异常", e);
            return Result.error("更新商机异常: " + e.getMessage());
        }
    }
    
    /**
     * 捞取商机
     * @param gainDto 捞取商机参数
     * @return 操作结果
     */
    @PutMapping("/gain")
    public Result<Void> gainBusiness(@RequestBody BusinessGainDto gainDto) {
        try {
            // 参数校验
            if (gainDto.getIds() == null || gainDto.getIds().isEmpty()) {
                return Result.error("请选择要捞取的商机");
            }
            
            if (gainDto.getUserId() == null) {
                return Result.error("用户ID不能为空");
            }
            
            // 将ID列表转换为逗号分隔的字符串
            String ids = String.join(",", gainDto.getIds().stream()
                    .map(String::valueOf)
                    .toArray(String[]::new));
            
            // 执行捞取操作
            boolean success = businessService.gainBusinesses(ids, gainDto.getUserId());
            
            if (success) {
                return Result.success();
            } else {
                return Result.error("捞取商机失败");
            }
        } catch (Exception e) {
            log.error("捞取商机异常", e);
            return Result.error("捞取商机异常: " + e.getMessage());
        }
    }
    
    /**
     * 退回公海
     * @param businessId 商机ID
     * @param reason 退回原因
     * @return 操作结果
     */
    @PutMapping("/back/{businessId}/{reason}")
    public Result<Void> backToPool(@PathVariable Integer businessId, @PathVariable String reason) {
        try {
            // 参数校验
            if (businessId == null) {
                return Result.error("商机ID不能为空");
            }
            
            if (reason == null || reason.isEmpty()) {
                return Result.error("请选择原因");
            }
            
            // 执行退回操作
            boolean success = businessService.backToPool(businessId, reason);
            
            if (success) {
                return Result.success();
            } else {
                return Result.error("退回公海失败");
            }
        } catch (Exception e) {
            log.error("退回公海异常", e);
            return Result.error("退回公海异常: " + e.getMessage());
        }
    }
    
    /**
     * 分配商机
     * @param assignmentDto 分配商机参数
     * @return 操作结果
     */
    @PutMapping("/assignment")
    public Result<Void> assignBusiness(@RequestBody BusinessAssignmentDto assignmentDto) {
        try {
            // 参数校验
            if (assignmentDto.getIds() == null || assignmentDto.getIds().isEmpty()) {
                return Result.error("请选择要分配的商机");
            }
            
            if (assignmentDto.getUserId() == null) {
                return Result.error("用户ID不能为空");
            }
            
            // 将ID列表转换为逗号分隔的字符串
            String ids = String.join(",", assignmentDto.getIds().stream()
                    .map(String::valueOf)
                    .toArray(String[]::new));
            
            // 执行分配操作
            boolean success = businessService.assignBusinesses(ids, assignmentDto.getUserId());
            
            if (success) {
                return Result.success();
            } else {
                return Result.error("分配商机失败");
            }
        } catch (Exception e) {
            log.error("分配商机异常", e);
            return Result.error("分配商机异常: " + e.getMessage());
        }
    }




}